package cn.alm.allinoneboot.service;

import cn.alm.allinoneboot.common.CommonResult;
import cn.alm.allinoneboot.entity.Category;
import cn.alm.allinoneboot.mapper.CategoryMapper;
import cn.alm.allinoneboot.utils.DateUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    // 新增分类
    public CommonResult addCategory(Category category) {
        String uuid = UUID.randomUUID().toString();
        category.setId(uuid);
        String currentDateWithFormat = DateUtil.getCurrentDateWithFormat();
        category.setCreateTime(currentDateWithFormat);
        category.setUpdateTime(currentDateWithFormat);
        int insert = categoryMapper.insert(category);
        CommonResult cr = new CommonResult();
        if (insert > 0) {
            cr.ok();
        } else {
            cr.error();
        }
        return cr;
    }

    // 更新分类
    public CommonResult updateCategory(Category category) {
        String currentDateWithFormat = DateUtil.getCurrentDateWithFormat();
        category.setUpdateTime(currentDateWithFormat);
        int update = categoryMapper.updateById(category);
        CommonResult cr = new CommonResult();
        if (update > 0) {
            cr.ok();
        } else {
            cr.error();
        }
        return cr;
    }

    public CommonResult getCategoryTree() {
        List<Category> categoryList = categoryMapper.selectList(null);
        Map<String, Category> categoryMap = new HashMap<>();
        for (Category category : categoryList) {
            categoryMap.put(category.getId(), category);
        }
        // 初始化树形结构，遍历所有节点并挂载到其父节点下
        for (Category category : categoryList) {
            String parentId = category.getParentId();
            if (parentId != null) {
                Category parentNode = categoryMap.get(parentId);
                if (parentNode != null) {
                    parentNode.addChild(category);
                }
            } else {
                // 如果parentId为空，则认为是根节点
                // 可以在此处直接处理根节点，或者将其添加到最终的树列表中
                // pass
            }
        }

        // 最终的根节点可能分布在nodeMap中，需要进一步提取出来
        List<Category> rootNodes = categoryList.stream()
                .filter(node -> node.getParentId() == null)
                .collect(Collectors.toList());

        CommonResult cr = new CommonResult();
        cr.ok();
        cr.setData(rootNodes);
        return cr;
    }

    public CommonResult deleteCategory(Category category) {
        int delete = categoryMapper.deleteById(category);
        CommonResult cr = new CommonResult();
        if (delete > 0) {
            cr.ok();
        } else {
            cr.error();
        }
        return cr;
    }


}
